package ext.tianma.part.util.updateIBAValues;

import java.io.Closeable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.Timestamp;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import ext.tianma.bom.util.QueryUtil;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.collections.WTArrayList;
import wt.method.RemoteAccess;
import wt.part.WTPart;
import wt.part.WTPartMaster;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.type.ClientTypedUtility;
import wt.type.TypeDefinitionForeignKey;
import wt.type.TypeDefinitionReference;
import wt.type.Typed;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.Iterated;
import wt.vc.config.ConfigHelper;
import wt.vc.config.ConfigSpec;
import wt.vc.config.LatestConfigSpec;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;

/**
 * 根据配置文件的查询规则查询部件
 * 
 * @author laichao_sun
 *
 */

public class QueryPart implements RemoteAccess, Serializable {

	private static final long serialVersionUID = 2807099851520072971L;
	public static String path = "/ptc/Windchill/codebase/ext/tianma/part/config/queryPart.xls";

	public static WTArrayList query() throws Exception {
		System.out.println("SLC=====开始根据配置文件进行查询最新部件=>");
		Workbook we = null;
		InputStream in = null;
		WTArrayList list = new WTArrayList();
		try {
			in = new FileInputStream(path);
			we = WorkbookFactory.create(in);
			if (null == path || path.equals("")) {
				throw new WTException("没有获取到部件查询条件的配置路径，请检查!");
			}
			if (null == in || null == we) {
				throw new WTException("没有获取到部件查询条件的配置路径，请检查!");
			}
			// 查询部件
			list = getPart(we.getSheetAt(0));
			System.out.println("SLC====部件的个数=>" + list.size());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InvalidFormatException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		} catch (WTPropertyVetoException e) {
			e.printStackTrace();
		} finally {
			close(in);
		}
		return list;

	}

	/**
	 * 通过配置文件查询部件
	 * 
	 * @return
	 * @throws Exception
	 */
	public static WTArrayList getPart(Sheet sheet) throws Exception {
		WTArrayList list = new WTArrayList();
		String code = null;
		QuerySpec qs = new QuerySpec(WTPart.class);
		qs.setAdvancedQueryEnabled(true);
		String condition = "";
		boolean flag = false;

		//System.out.println("sheet.getLastRowNum():" + sheet.getLastRowNum());
		for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
			Row row = sheet.getRow(i);
			String temp = getCellValue(row.getCell(0)).trim();
			if (null == temp || temp.equals("")) {
				continue;
			} else {
				if(temp.equals("料号")) {
					code = getCellValue(row.getCell(1)).trim();
					if (code.indexOf("*") != -1) {
						condition = SearchCondition.LIKE;
						code = code.substring(code.indexOf("*") + 1);
					} else if (code.indexOf("!") != -1) {
						condition = SearchCondition.NOT_EQUAL;
						code = code.substring(code.indexOf("!") + 1);
					} else {
						condition = SearchCondition.EQUAL;
					}
					//编号查询
					SearchCondition sc0 = new SearchCondition(WTPart.class, wt.part.WTPart.NUMBER,condition,
							code);
					qs.appendWhere(sc0);

					flag = true;
				}else if (temp.equals("类型")) {
					code = getCellValue(row.getCell(1)).trim();
					TypeDefinitionReference clientType = ClientTypedUtility.getTypeDefinitionReference(code);
					SearchCondition sc = new SearchCondition(WTPart.class,
							Typed.TYPE_DEFINITION_REFERENCE + "." + TypeDefinitionReference.KEY + "."
									+ TypeDefinitionForeignKey.BRANCH_ID,
							SearchCondition.EQUAL, clientType.getKey().getBranchId());
					qs.appendWhere(sc, new int[] { 0 });
					flag = true;
				} else if (temp.equals("视图")) {
					code = getCellValue(row.getCell(1)).trim();
					if (code.indexOf("*") != -1) {
						condition = SearchCondition.LIKE;
						code = code.substring(code.indexOf("*") + 1);
					} else if (code.indexOf("!") != -1) {
						condition = SearchCondition.NOT_EQUAL;
						code = code.substring(code.indexOf("!") + 1);
					} else {
						condition = SearchCondition.EQUAL;
					}
					View view = ViewHelper.service.getView(code);
					SearchCondition sc1 = new SearchCondition(WTPart.class, "view.key.id",condition,
							view.getPersistInfo().getObjectIdentifier().getId());
					//System.out.println("视图 view.key.id:" + view.getPersistInfo().getObjectIdentifier().getId());
					qs.appendWhere(sc1);
					flag = true;
				} else if (temp.equals("状态")) {
					code = getCellValue(row.getCell(1)).trim();
					if (code.indexOf("*") != -1) {
						condition = SearchCondition.LIKE;
						code = code.substring(code.indexOf("*") + 1);
					} else if (code.indexOf("!") != -1) {
						condition = SearchCondition.NOT_EQUAL;
						code = code.substring(code.indexOf("!") + 1);
					} else {
						condition = SearchCondition.EQUAL;
					}
					SearchCondition sc2 = new SearchCondition(WTPart.class, WTPart.LIFE_CYCLE_STATE, condition, code);
					qs.appendWhere(sc2, new int[] { 0 });
					flag = true;
				} else if (temp.equals("开始时间")) {
					code = getCellValue(row.getCell(1));
					Timestamp beginDate = Timestamp.valueOf(code);
					//System.out.println("beginDate:" + beginDate);
					SearchCondition sc3 = new SearchCondition(WTPart.class, WTPart.CREATE_TIMESTAMP,
							SearchCondition.GREATER_THAN_OR_EQUAL, beginDate);
					qs.appendWhere(sc3);
					flag = true;
				} else if (temp.equals("结束时间")) {
					code = getCellValue(row.getCell(1));
					Timestamp finshDate = Timestamp.valueOf(code);
					//System.out.println("finshDate:" + finshDate);
					SearchCondition sc4 = new SearchCondition(WTPart.class, WTPart.CREATE_TIMESTAMP,
							SearchCondition.LESS_THAN_OR_EQUAL, finshDate);
					qs.appendWhere(sc4);
					flag = true;
				} else if (flag == false) {
					code = getCellValue(row.getCell(1)).trim();
					//System.out.println("软属性的值" + code);
					if (code.indexOf("*") != -1) {
						condition = SearchCondition.LIKE;
						code = code.substring(code.indexOf("*") + 1);
					} else if (code.indexOf("!") != -1) {
						condition = SearchCondition.NOT_EQUAL;
						code = code.substring(code.indexOf("!") + 1);
					} else {
						condition = SearchCondition.EQUAL;
					}
					qs.appendWhere(QueryUtil.getIBASearchCondition(WTPart.class, temp, code, condition),
							new int[] { 0 });
					flag = true;
				}
				if (i == sheet.getLastRowNum()) {
					break;
				}
				if (flag == true) {
					qs.appendAnd();
					flag = false;
				}
			}

		}
		// 查询部件
		System.out.println("SLC=========qs==>>" + qs.toString());
		QueryResult qr = PersistenceHelper.manager.find(qs);
		System.out.println("SLC=========qs==>>" + qr);
		qr = new LatestConfigSpec().process(qr);
		while (qr.hasMoreElements()) {
			WTPart part = (WTPart) qr.nextElement();
			list.add(part);
			//System.out.println("SLC..............result:" + part.getNumber() + " | " + part.getViewName());
		}
		return list;
	}

	/**
	 * 获取最新的部件
	 * 
	 * @param paramWTPartMaster
	 * @return
	 * @throws WTException
	 */
	public static WTPart getLatestPartByPartMaster(WTPartMaster paramWTPartMaster) throws WTException {
		Iterated localIterated = null;
		boolean bool = false;
		LatestConfigSpec localLatestConfigSpec = new LatestConfigSpec();

		QueryResult localQueryResult = ConfigHelper.service.filteredIterationsOf(paramWTPartMaster,
				localLatestConfigSpec);
		if ((localQueryResult != null) && (localQueryResult.size() <= 0)) {
			ConfigSpec localConfigSpec = ConfigHelper.service.getDefaultConfigSpecFor(WTPartMaster.class);
			localQueryResult = ConfigHelper.service.filteredIterationsOf(paramWTPartMaster, localConfigSpec);
		}

		while ((localQueryResult.hasMoreElements()) && (!bool)) {
			localIterated = (Iterated) localQueryResult.nextElement();
			bool = localIterated.isLatestIteration();
		}
		return (WTPart) localIterated;
	}

	/**
	 * 空或者NULL值时返回true
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNullOrEmpty(String str) {
		return (str == null || "".equals(str) || str.equals("null") || str.equals("NULL"));
	}

	/**
	 * 获取单元格中的信息
	 * 
	 * @param cell 单元格
	 * @return 主要参数信息
	 * @throws Exception
	 */
	public static String getCellValue(Cell cell) throws WTException {
		String value = "";
		try {
			if (null == cell) {
				return "";
			}
			switch (cell.getCellType()) {
			case XSSFCell.CELL_TYPE_NUMERIC:
				value = Double.toString(cell.getNumericCellValue());
				break;
			case XSSFCell.CELL_TYPE_STRING:
				value = cell.getStringCellValue();
				break;
			case XSSFCell.CELL_TYPE_BLANK:
				value = "";
				break;
			case XSSFCell.CELL_TYPE_BOOLEAN:
				value = Boolean.toString(cell.getBooleanCellValue());
				break;
			case XSSFCell.CELL_TYPE_FORMULA:
				try {
					value = String.valueOf(cell.getNumericCellValue());
				} catch (Exception e) {
					value = cell.getStringCellValue();
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
		}
		return value.trim();
	}

	/**
	 * 关闭资源
	 * 
	 * @param closeable
	 */
	public static void close(Closeable closeable) {
		try {
			if (closeable != null) {
				closeable.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
